<?php

// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use think\Db;
use think\Validate;
use think\Session;

/**
 * 系统会员管理
 * Class Members
 * @package app\admin\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/02/15 18:12
 */
class Members extends BasicAdmin
{

    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'ShopMembers';

    /**
     * 会员列表
     */
    public function index()
    {
        $this->title = '会员列表';
        $get = $this->request->get();
        $db = Db::name($this->table)
                ->where('is_deleted',0);

        foreach (['title'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        // if (isset($get['date']) && $get['date'] !== '') {
        //     list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
        //     $db->whereBetween('login_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        // }
        return parent::_list($db);
    }

    /**
     * 会员添加
     */
    public function add()
    {
        return $this->_form($this->table, 'form');
    }

    /**
     * 添加会员动作
     */
    public function action_add()
    {
        // 接收数据
        $msg = $this->request->post();
    
        // 数据验证
        $rule = [
            ['uname','require|unique:shop_members,uname','会员名称不能为空|会员名已存在'],
            ['password','require','密码不能为空'],
        ];
        $data = [
            'uname'  => $msg['uname'],
            'password'   => $msg['password'],
        ];

        $validate = new Validate($rule);
        $result   = $validate->check($data);

        if(!$result){
            $this->error($validate->getError());
        }
        // 生成token
        $token = str_rand().date('YmdHis',time());

        // 准备添加数据
        $new_data = [
            'uname'     => $msg['uname'],
            'password'  => md5($msg['password'].$token),
            'token'     => $token,
            'type'      => 3,
            'head_portrait' => DEFAULT_HEAD_PORTRAIT,
        ];

        $res = Db::name('shop_members')
                ->insert($new_data);

        if($res !== false){
            $this->success('添加成功','');
        }else{
            $this->error('添加失败，请稍后在试！');
        }

    }

    /**
     * 会员编辑
     */
    public function edit()
    {
        return $this->_form($this->table, 'form');
    }

    /**
     * 会员编辑动作
     * @return [type] [description]
     */
    public function action_edit()
    {

        $msg = $this->request->post();

        $data = [];
        // 检测昵称
        if(!empty($msg['nickname']) && isset($msg['nickname'])){
            $res = Db::name($this->table)
                    ->field('id')
                    ->where('nickname',$msg['nickname'])
                    ->where('id','<>',$msg['id'])
                    ->find();
            if(!empty($res)){
                $this->error('昵称已存在！');
            }
            $data['nickname'] = $msg['nickname'];
        }
        // 检测头像
        if(!empty($msg['head_portrait']) && isset($msg['head_portrait'])){
            // 处理头像数据
            $msg['head_portrait'] = ltrim($msg['head_portrait'],pathinfo(request()->baseFile(true), PATHINFO_DIRNAME));
            $data['head_portrait'] = $msg['head_portrait'];
        }

        $data['sex'] = $msg['sex'];

        if(!empty($data)){
            $res = Db::name($this->table)
                    ->where('id',$msg['id'])
                    ->update($data);
            if($res !== false){
                $this->success('修改成功','');
            }else{
                $this->error('修改失败，请稍后再试！');
            }
        }
    }
    
     /**
     * 会员邮箱验证
     */
    public function email()
    {
        if ($this->request->isGet()) {
            $this->assign('verify', true);
            return $this->_form($this->table, 'email');
        }
        $post = $this->request->post();
      
        $code =  Session::get('email'.$post['id']);

        if($code != $post['email_code']){
            $this->error('验证码错误');
        }
  
        $res = Db::name('shop_members')
                    ->where('id',$post['id'])
                    ->update(['email' => $post['email']]);
        if($res !== false){
            $this->success('验证邮箱成功！','');
        }else{
            $this->error('验证邮箱失败！');
        }
    }

    /**
     * 获取邮箱验证码
     * @return [type] [description]
     */
    public function get_email_code()
    {
        $post = $this->request->post();
        // 查询该邮箱是否存在
        $email = Db::name('shop_members')
                    ->field('id')
                    ->where('email',$post['email'])
                    ->find();
        if(!empty($email)){
            return json(['code' => 400,'message' => '邮箱号已存在！']);
        }

        // 生成验证码
        $rand = mt_rand(100000,999999);
        // 存储到session中
        Session::set('email'.$post['id'],$rand);
        
        // 发送邮件
        $data = [
            'to_email'  => $post['email'],
            'subject'   => '红酒交易中心用户验证',
            'body'      => '账户邮箱验证码：'.$rand,
        ];
        $res = send_email($data);

        if($res !== 1){
            return json(['code' => 400,'message' => '邮件发送失败！']);
        }else{
            return json(['code' => 200,'message' => '邮件发送成功！']);
        }
    }

    /**
     * 会员密码修改
     */
    public function pass()
    {
        if ($this->request->isGet()) {
            $this->assign('verify', true);
            return $this->_form($this->table, 'pass');
        }
        $post = $this->request->post();
        if ($post['password'] !== $post['repassword']) {
            $this->error('两次输入的密码不一致！');
        }

        // 查询该用户token
        $token = Db::name($this->table)
                    ->field('token')
                    ->where('id',$post['id'])
                    ->find()['token'];
        // 判断旧密码是否正确
        $res = Db::name($this->table)
                    ->field('id')
                    ->where('password',md5($post['oldpassword'].$token))
                    ->where('id',$post['id'])
                    ->find();
        if(empty($res)){
            $this->error('旧的密码不正确！');
        }

        $data = ['id' => $post['id'], 'password' => md5($post['password'].$token)];
        if (DataService::save($this->table, $data, 'id')) {
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }


    /**
     * 删除会员
     */
    public function del()
    {
        if (DataService::update($this->table)) {
            $this->success("会员删除成功！", '');
        }
        $this->error("会员删除失败，请稍候再试！");
    }

    /**
     * 会员禁止
     */
    public function forbid()
    {
        if (DataService::update($this->table)) {
            $this->success("会员禁止成功！", '');
        }
        $this->error("会员禁止失败，请稍候再试！");
    }

    /**
     * 会员启用
     */
    public function resume()
    {
        if (DataService::update($this->table)) {
            $this->success("会员启用成功！", '');
        }
        $this->error("会员启用失败，请稍候再试！");
    }

}
